package cn.lingyangwl.agile.pay.pay.listener;

import cn.lingyangwl.agile.pay.common.model.mq.ErrorMQ;
import cn.lingyangwl.framework.mq.base.manager.MqManager;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author shenguangyang
 */
@Slf4j
@Component
@RabbitListener(bindings = {
        @QueueBinding(
                value = @Queue(value = ErrorMQ.QUEUE, durable = "true"), key = ErrorMQ.KEY,
                exchange = @Exchange(value = ErrorMQ.EXCHANGE, type = ExchangeTypes.TOPIC))
})
public class OrderErrorListener {
    @Resource
    private MqManager mqManager;

    @RabbitHandler
    public void onMessage(@Payload(required = false) String msg, Channel channel, Message message) {
        Map<String, Object> headers = message.getMessageProperties().getHeaders();
        Object exceptionMessage = headers.get("x-exception-message");
        Object exceptionStacktrace = headers.get("x-exception-stacktrace");
        Object originalExchange = headers.get("x-original-exchange");
        Object originalRoutingKey = headers.get("x-original-routingKey");
        log.error("originalExchange: {}, originalRoutingKey: {}, exceptionMessage: {}, exceptionStacktrace: {}",
                originalExchange, originalRoutingKey, exceptionMessage, exceptionStacktrace);
        try {
            ErrorMQ.MsgPayload msgPayload = ErrorMQ.parse(msg);
            log.info("消费成功: {}", msgPayload.toJSONString());
            log.info("告警发送短信成功...");
        } catch (Exception e) {
            log.error("消费失败: {}", e.getMessage());
        }
    }
}
